package com.docHunt.Util;

import java.security.MessageDigest;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class AppUtil {

	private static ResourceBundle mailConfig = ResourceBundle.getBundle("mail");
	private static Logger logger = Logger.getLogger(AppUtil.class);

	public static String generateVerificationCode(String loginId)
			throws Exception {

		MessageDigest md = MessageDigest.getInstance("SHA1");
		md.reset();
		byte[] buffer = loginId.getBytes();
		md.update(buffer);
		byte[] digest = md.digest();

		String hexStr = "";
		for (int i = 0; i < 4/* digest.length */; i++) {
			hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16)
					.substring(1);
		}
		return hexStr;

	}

	public static boolean sendMail(String toMailId, String mailSubject,
			String mailBody) throws Exception {

		boolean ret = true;

		String host = mailConfig.getString("mail.smtp.host");
		String from = mailConfig.getString("mail.smtp.user");
		String pass = mailConfig.getString("mail.smtp.password");
		String port = mailConfig.getString("mail.smtp.port");
		String auth = mailConfig.getString("mail.smtp.auth");

		Properties props = System.getProperties();
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.user", from);
		props.put("mail.smtp.password", pass);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", auth);

		try {
			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));

			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(toMailId));

			message.setSubject(mailSubject);
			message.setText(mailBody);

			Transport transport = session.getTransport("smtp");
			transport.connect(host, from, pass);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			ret = false;
			logger.error("AppUtil :: Exception in method sendMail: ", e);
		}

		return ret;
	}
}
